package com.glory.hikvisionmobile.activity;


import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.LotSplitListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.LotSplitOrAdd.LotSplitBean;
import com.glory.hikvisionmobile.bean.LotSplitOrAdd.PdaComponentBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.MyUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Lot_LotSplitActivity extends BaseActivity {


    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvStepDetails)
    TextView tvStepDetails;
    @BindView(R.id.tvRecipe)
    TextView tvRecipe;
    @BindView(R.id.tvProductDetails)
    TextView tvProductDetails;
    @BindView(R.id.tvLotNumber)
    TextView tvLotNumber;
    @BindView(R.id.etLotNum)
    FreeUI_ClearEditText etLotNum;
    @BindView(R.id.rvLotSplitList)
    RecyclerView rvLotSplitList;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.tvPartName)
    TextView tvPartName;
    @BindView(R.id.tvRecipeDesc)
    TextView tvRecipeDesc;
    @BindView(R.id.etLotNumber)
    EditText etLotNumber;
    @BindView(R.id.etSpiltLot)
    FreeUI_ClearEditText etSpiltLot;
    @BindView(R.id.llSpiltLotLayout)
    LinearLayout llSpiltLotLayout;
    @BindView(R.id.llSpiltPartLayout)
    LinearLayout llSpiltPartLayout;
    private LotSplitListAdapter lotSplitListAdapter;
    private List<PdaComponentBean> pdaComponentBeans = new ArrayList<>();
    private String subUnitType;
    private LotSplitBean lotSplitBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lot_split;
    }

    @Override
    protected void initView() {
        initListTitle();
        rvLotSplitList.setLayoutManager(new LinearLayoutManager(Lot_LotSplitActivity.this));
        rvLotSplitList.setItemAnimator(new DefaultItemAnimator());
        rvLotSplitList.addItemDecoration(new DividerItemDecoration(Lot_LotSplitActivity.this, 1));
        lotSplitListAdapter = new LotSplitListAdapter(null);
        lotSplitListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lotSplitListAdapter.isFirstOnly(true);
        rvLotSplitList.setAdapter(lotSplitListAdapter);
        initEdit(etLot, s -> requestDataForNet(s));
        FreeApi_EditTextUtils.setEditTextListener(etLotNum, this, s -> {
            checkData(s);
        });
        MyUtils.editActionListener(etLotNumber, s -> {
            addLot(s);
        });

    }

    private void addLot(String number) {
        int num = Integer.parseInt(number);
        if (num <= 0) {
            showToast("组件数量不能小于0", false);
            return;
        }

        if (pdaComponentBeans.size() <= 0) {
            showToast("未获取到组件数据", false);
            return;
        }

        if (num > pdaComponentBeans.size()) {
            showToast("组件数量不能大于可分组件数量", false);
            return;
        }

        SparseBooleanArray dataCheck = lotSplitListAdapter.getDataCheck();
        dataCheck.clear();
        for (int i = 0; i < num; i++) {
            dataCheck.put(i, true);
        }
        lotSplitListAdapter.notifyDataSetChanged();
    }

    private void checkData(String partID) {
        String isCheck = "N";
        List<PdaComponentBean> data = lotSplitListAdapter.getData();
        if (data.size() <= 0) {
            showToast("未获取到数据", false);
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getComponentId().equals(partID)) {
                if (!lotSplitListAdapter.getDataCheck().get(i, false)) {
                    isCheck = "Y";
                    lotSplitListAdapter.getDataCheck().put(i, true);
                    lotSplitListAdapter.notifyItemChanged(i);
                    etLotNum.requestFocus();
                    etLotNum.setText("");
                    break;
                }
            }
        }

        if (isCheck.equals("N")) {
            showConfirmDialog("当前组件不在列表内");
            etLotNum.setText("");
            etLotNum.requestFocus();
        }


    }


    @Override
    protected void initData() {
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("批次分批");
        freeUI_titleView.setRightListener("刷新", v -> {

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    if (editIsEmpty(etLot, "批次号不能为空")) {
                        lotSplitListAdapter.clearPos();
                        lotSplitListAdapter.notifyDataSetChanged();
                        etSpiltLot.setText("");
                        etLotNumber.setText("");
                        etLotNum.setText("");
                        requestDataForNet(etLot.getText().toString().trim());
                    }
                }
            });



        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void requestDataForNet(String lotID) {
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lotID);
        NetUtils.requestDara("HIK.PdaLotSplit", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LotSplitBean>>(
                new TypeToken<BaseResponseBean<LotSplitBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotSplitBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    lotSplitBean = response.body().getBody();
                    tvLotNumber.setText(lotSplitBean.getMainQty());
                    tvProductDetails.setText(lotSplitBean.getPartDesc());
                    tvRecipe.setText(lotSplitBean.getRecipeName());
                    tvStepDetails.setText(lotSplitBean.getStepDesc());
                    pdaComponentBeans = lotSplitBean.getxPdaComponents();
                    lotSplitListAdapter.setNewData(pdaComponentBeans);
                    tvPartName.setText(lotSplitBean.getPartName());
                    tvRecipeDesc.setText(lotSplitBean.getRecipeDesc());
                    subUnitType = lotSplitBean.getSubUnitType();
                    if (subUnitType.equals("ComponentUnit")){
                        llSpiltLotLayout.setVisibility(View.GONE);
                        llSpiltPartLayout.setVisibility(View.VISIBLE);
                    }else {
                        llSpiltLotLayout.setVisibility(View.VISIBLE);
                        llSpiltPartLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotSplitBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotSplit");

            }
        });
    }


    @OnClick(R.id.tvReplay)
    public void onViewClicked() {

        initPermission("Submit", this, new ActionControlListener() {
            @Override
            public void onControlChangeListener() {
                if (subUnitType.equals("ComponentUnit")){
                    if (lotSplitListAdapter.getCommentID().length() == 0) {
                        showToast("请选择分批组件", false);
                        return;
                    }
                    DialogUtils.showLoginDialog(Lot_LotSplitActivity.this, Constant.CURRENT_USER, () -> {
                        submit(etLot.getText().toString().trim());
                    }, getSupportFragmentManager());

                }else {
                    String qtyNum = tvLotNumber.getText().toString().trim();
                    if (qtyNum.length() == 0){
                        showToast("未请求到数据", false);
                        return;
                    }
                    if (editIsEmpty(etSpiltLot,"请输入分批数量")){
                        int spiltNum = Integer.parseInt(etSpiltLot.getText().toString().trim());
                        int qtyNums = Integer.parseInt(qtyNum);
                        if (spiltNum <= 0){
                            showToast("分批数量不能小于0", false);
                            etSpiltLot.setText("");
                            etSpiltLot.requestFocus();
                            return;
                        }
                        if (spiltNum > qtyNums){
                            showToast("分批数量不能大于批数量", false);
                            etSpiltLot.setText("");
                            etSpiltLot.requestFocus();
                        }else {
                            DialogUtils.showLoginDialog(Lot_LotSplitActivity.this, Constant.CURRENT_USER, () -> {
                                submit(etLot.getText().toString().trim());
                            }, getSupportFragmentManager());
                        }
                    }
                }
            }
        });

    }

    private void submit(String lotID) {
        JsonObject map = new JsonObject();
        map.addProperty("lotId", lotID);
        map.addProperty("actionType", "Split");
        map.addProperty("componentIdList", lotSplitListAdapter.getCommentID());
        map.addProperty("splitMainQty",etSpiltLot.getText().toString().trim());
        NetUtils.requestDara("HIK.PdaLotSplit", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LotSplitBean>>(
                new TypeToken<BaseResponseBean<LotSplitBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotSplitBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    showConfirmDialog(Lot_LotSplitActivity.this, "分批成功，子批：" + response.body().getBody().getChildLotId());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotSplitBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaLotSplit");

            }
        });
    }

    private void initListTitle() {
        listTv1.setText("组件号");
        listTv2.setText("位置");
        listTv3.setText("状态");
        listTv4.setText("主数量");
        listTv5.setText("复选框");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
    }

}
